<?php
include($configRootDir."core/response.php");
include($configRootDir."core/request.php");
include($configRootDir."core/database.php");
include($configRootDir."core/logs.php");
include($configRootDir."core/accessRights.php");


/**
 * Dispatcher
 *
 * Runs the good Controller, depending the request, and send the response.
 *
 *
 * @copyright inovia
 * @package oolime_core   
 *
 */
class Dispatcher {
	public  $database;
	public  $response;
	public  $request;
	public  $session;
	public  $user;
	public  $usergroup;
	private $logs;
	private $output;
	private $accessRights;
	
	/**
	 * Dispatcher constructor
	 * @todo Log errors
	 */
	function __construct(){
	  global $logs;
    global $database;
    global $response;
    global $request;
    global $session;
    global $user;
    global $usergroup;
    global $configDispatcher;
    global $configMaintenance;
    
    $this->logs       = &$logs;
    $this->database   = &$database;
    $this->response   = &$response;
    $this->request    = &$request;
    $this->session    = &$session;
    $this->user       = &$user;
    $this->usergroup  = &$usergroup;

    $this->accessRights = new accessRights();
    $this->logs         = new Logs();
		$this->database     = new Database();
		$this->response     = new Response();
    $this->session      = new Session();
    
    // retrieves cookie informations if exist and init the session with
    if (isset($_COOKIE['oolime']) && isset($_COOKIE['oolime']['login']) && isset($_COOKIE['oolime']['password']) ) {
      $isSessionOk = $this->session->init($_COOKIE['oolime']['login'],$_COOKIE['oolime']['password']);
    // retrieves session informations if exist and init the session with
    }else if(isset($_SESSION['login']) && isset($_SESSION['password'])) {
      $isSessionOk = $this->session->init($_SESSION['login'],$_SESSION['password']);
    // inits the default session
    }else{
      $isSessionOk = $this->session->init('','');
    }
    
    $this->response->initSession(); 
    $this->request = new Request();


    // EventDispatcher's switch
		$action     = $this->request->getValueD('action');
		if(isset($configDispatcher[$action]))		$controller = $configDispatcher[$action];
    else                                    $controller = null;
    
    //init rights
    $this->accessRights->initUserGroup();
	    
		// maintenance case
		if($configMaintenance && isset($this->user->field->group) && $this->accessRights->inheritsFromGroup($this->user->field->group,'manager') && $controller[3]){
      $this->output = 'xsl';
      $this->response->setXSLT("views/maintenance.xsl");

		// no maintenance
		}else{

	    
      //if the controller exists and the action is not false
      if(($controller != null) && ($action!=false)){
        if(isset($this->user) && $this->accessRights->isActionAllowed($action)){
        //if ($this->session->check($controller[2])){
          $this->output = $controller[2];
					$this->execController($controller[0],$controller[1]);
					
				// The session hasn't the rights 
				}else{
				  if(isset($_SESSION['login'])) $this->logs->logWarning("User ".$_SESSION['login']." tried to execute action ".$action." without rights");
          else $this->logs->logWarning("User unknown tried to execute action ".$action." without rights");
				  
          $this->execController('login','core/');
        }
        
      // False action or missing controller
      }else{
        $this->execDefaultController();
      }
    }
		
		//executes the output
		$this->outputs();

    /**
     * Need to force destructors of instances
     * if not done, failed to find database for these mapped objects          
     */         
		$this->user       = null;
		$this->usergroup  = null;
    $this->database   = null;
		
	}


  /**
   * Executes a controller
   * @param string the controller name
   * @param string the relative path to access the controller
   */        
	public function execController($controller, $relpath){
		global $configRootDir;
    
		/* Includes the Controller, takes the constructor, makes an new object then destroy it */
		$path = $configRootDir.$relpath.$controller.".php";
		if(file_exists($path)){
		  include($path);
		  $obj  = new $controller();
		  $obj  = null;
		}else{
      $this->logs->logError("Unable to locate the controller ".$path);
      $this->execDefaultController();
    }
	}
	
	/**
	 * Executes the default controller
	 */   	
	public function execDefaultController(){
		global $configRootDir;
    global $configControllerDefault;
    global $configControllerDefaultPath;
    $this->output = 'xsl';
    $path = $configRootDir.$configControllerDefaultPath.$configControllerDefault.".php";
    if(file_exists($path)){
		  include($path);
		  $obj  = new $configControllerDefault();
		  $obj  = null;
		}else{
      $this->logs->logError("Unable to locate the default controller ".$path);
      die(0);
    }
  }
	
	/**
	 *  Executes the output
	 */   	
	public function outputs(){
	  global $configDebugXSLT;
	  
    if ($configDebugXSLT || $this->session->exportXML || ($this->output=='xml' && !$this->session->exportJSON)) {
      header("Content-Type: application/xml; charset=ISO-8859-1");
			$this->response->finalize(false);
		}else if($this->session->exportJSON || $this->output=='json'){
			$this->response->setXSLT("ressources/xml2json.xsl");
			echo $this->response->processXSLT();
		}else{
			echo $this->response->processXSLT();
		}
  }

}

?>
